from flask import render_template, request, send_file, Blueprint, redirect, url_for
from flask import current_app as app
import os
from pdf2img import do_pdf_2_img
from utils import get_file_info, get_timestamp, get_file_paths, create_zip_file

bp = Blueprint('pdf2img_routes', __name__, template_folder="templates")


@bp.route("/pdf2img")
def pdf2img():
    data = {}
    return render_template("pdf2img/pdf2img.html", title="pdf2img", data=data)


@bp.route("/upload", methods=["POST"])
def upload_file():
    if request.method == "POST":
        if 'file' not in request.files:
            return 'No file part'

        file = request.files['file']
        if file.filename == '':
            return 'No selected file'

        filename = file.filename
        # 获取文件类型
        file_info = get_file_info(filename)
        if file_info[1] != "pdf":
            return 'File is not pdf'

        if file:
            ts = get_timestamp()
            file_name_ts = file_info[0] + "_" + ts  # 2021200151_1712548660
            new_filename = file_name_ts + "." + file_info[1]  # 2021200151_1712548660.pdf

            print(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))

            # 转存图片
            do_pdf_2_img(new_filename)

            return redirect(url_for("pdf2img_routes.to_download", folder_name=file_name_ts))


@bp.route("/to_download/<folder_name>")
def to_download(folder_name):
    img_path = os.path.join(app.config['DOWNLOAD_FOLDER'], folder_name)
    print("folder_name:", img_path)
    file_paths = get_file_paths(img_path)
    data = {
        "img_path": img_path.replace("\\", "/"),
        "file_paths": file_paths
    }
    return render_template("pdf2img/download.html", title="download", data=data)


@bp.route("/download", methods=["POST"])
def download():
    selected_images = request.form.getlist('selectedImages[]')

    img_path = request.form["img_path"]  # 2img/2021200151_1712549255

    zip_path = os.path.join(img_path, img_path.split("/")[1] + ".zip").replace("\\", "/")
    print("start zip, zip_path:", zip_path)
    create_zip_file(selected_images, zip_path)

    return redirect(url_for("pdf2img_routes.do_download", zip_path=zip_path))
    # return send_file(zip_path, as_attachment=True)


@bp.route("/do_download/<path:zip_path>", methods=["GET"])
def do_download(zip_path):
    print("do_download, zip_path:", zip_path)
    return send_file(zip_path, as_attachment=True)
